import type {
  ConsultOrderItem,
  ConsultOrderListParams,
  ConsultOrderPage,
  ConsultOrderPreData,
  ConsultOrderPreParams,
  DoctorPage,
  FollowType,
  Image,
  KnowledgePage,
  KnowledgeParams,
  PageParams,
  PartialConsult,
  Dep,
  Consult,
  Doctor
} from '@/types/consult'
import type { TimeMessages, Message } from '@/types/room'
import type { MessageListResponse, ConversationInfo } from '@/types/user'

import { request } from '@/utils/request'
import axios from 'axios'

export const getKnowledgePage = async (params: KnowledgeParams) => {
  const baseUrl = import.meta.env.VITE_APP_OTHER_BASE_URL
  const res = await axios.post(baseUrl + '/login/password', {
    mobile: '13230000001',
    password: 'abc12345'
  })
  const token = res.data.data.token
  return await axios.get(baseUrl + '/patient/home/knowledge', {
    params,
    headers: { Authorization: `Bearer ${token}` }
  })
}

export const getDoctorPage = (params: PageParams) =>
  request.get<DoctorPage>('home/page/doc', { params })

export const followOrUnfollow = (id: string, type: FollowType = 'doc') =>
  request.post('like', { id, type })

export const getAllDep = () => request.get<Dep[]>('consult/dep/all')

export const uploadImage = (file: File, consultId: string) => {
  const image = new FormData()
  image.append('file', file)
  return request.post('/consult/upload/images/' + consultId, image)
}

export const getConsultOrderPre = (doctorId: string) =>
  request.get<ConsultOrderPreData>('consult/price/' + doctorId)

export const createConsultOrder = async (data: Consult) =>
  await request.post('consult/order/add', data)

export const getConsultOrderDetail = async (id: string) =>
  request.get('patient/consult/order/detail/' + id)

export const getPrescriptionPic = (id: string) =>
  request.get<{ url: string }>(`patient/consult/prescription/${id}`)

export const evaluateConsultOrder = (data: {
  docId: string
  orderId: string
  score: number
  content: string
  anonymousFlag: 0 | 1
}) => request.post('patient/order/evaluate', data)

export const getConsultOrderList = (params: ConsultOrderListParams) =>
  request.get('/patient/consult/order/list', { params })

export const cancelOrder = (id: string) =>
  request.put(`patient/order/cancel/${id}`)

export const deleteOrder = (id: string) => request.delete(`patient/order/${id}`)

// 获取医生列表
export const getDoctorList = (params: {
  keyword?: string
  location?: string
  departmentId?: number
  sortBy?: 'rating' | 'price' | 'consultCount'
  sortOrder?: 'asc' | 'desc'
  pageNum?: number
  pageSize?: number
}) => {
  return request.get<{
    errorCode: null | string
    success: boolean
    data: {
      id: string
      doctorName: string
      personalResume: string | null
      message: string | null
      expertise: string | null
      socialPosition: string | null
      awards: string | null
      researchAchievements: string | null
      price: number
      avatar: string
      departments: string | null
    }[]
  }>('/doctor/list', { params })
}

// 获取医生详情
export const getDoctorDetail = (id: string) => {
  return request.get<{
    errorCode: null | string
    success: boolean
    data: {
      id: string
      doctorName: string
      personalResume: string | null
      message: string | null
      expertise: string | null
      socialPosition: string | null
      awards: string | null
      researchAchievements: string | null
      price: number
      avatar: string
      departments: string | null
    }
  }>(`/doctor/${id}`)
}

// 获取聊天消息列表
export const getChatMessageList = (orderId: string, lastTime?: string) => {
  return request.get<TimeMessages[]>(`chat/order/${orderId}/messages`, {
    params: {
      lastTime
    }
  })
}

// 发送聊天消息
export const sendChatMessage = (data: {
  orderId: string
  msgType: number
  content?: string
  picture?: Image
  fromUser?: string
  toUser?: string
}) => {
  return request.post<Message>('chat/message/send', data)
}

// 更新消息状态（已读）
export const updateMessageStatus = (messageId: string) => {
  return request.put(`chat/message/${messageId}/read`)
}

// 获取用户消息列表（会话列表）- 支持分页和排序
export const getMessageList = (
  userId: string,
  page: number = 1,
  size: number = 10,
  sortByUnread: boolean = true
) => {
  return request.get<MessageListResponse>(`chat/message-list/${userId}`, {
    params: { page, size, sortByUnread }
  })
}

// 获取用户头像
export const getUserAvatar = (userId: string) => {
  return request.get<string>(`chat/user/avatar/${userId}`)
}

// 获取未读消息总数
export const getUnreadMessageCount = (userId: string) => {
  return request.get<number>(`chat/unread-count/${userId}`)
}

// 获取指定会话的未读消息数量
export const getUnreadMessageCountByConsult = (
  consultId: string,
  userId: string
) => {
  return request.get<number>(`chat/unread-count/${consultId}/${userId}`)
}

// 标记指定会话的所有消息为已读
export const markMessagesAsRead = (consultId: string, userId: string) => {
  return request.put<string>(`chat/mark-read/${consultId}/${userId}`)
}

// 获取会话信息（包含最新消息、未读数等）
export const getConversationInfo = (consultId: string, userId: string) => {
  return request.get<ConversationInfo>(
    `chat/conversation/${consultId}/${userId}`
  )
}

// 获取最新消息
export const getLatestMessage = (consultId: string) => {
  return request.get<Message>(`chat/latest-message/${consultId}`)
}

// 清除所有未读消息
export const clearAllUnreadMessages = (userId: string) => {
  return request.put<string>(`chat/clear-all-unread/${userId}`)
}
